import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:shared_preferences/shared_preferences.dart' as prefix0;

import '../const.dart';

class MyDio {
  static final String GET = "GET";
  static final String POST = "POST";
  static final String DATA = "data";
  static final String CODE = "code";
  static var codes = {0, 1, 200};

  Dio dio;
  static MyDio _instance;

  static MyDio getInstance({String url}) {
    if (_instance == null) {
      _instance = MyDio(url: url);
    }
    return _instance;
  }

  MyDio({String url}) {
    var baseUrl;
    url == null ? baseUrl = Const.BASEURL : baseUrl = url;
    dio = Dio(BaseOptions(
      baseUrl: baseUrl,
      connectTimeout: 5000,
      receiveTimeout: 5000,
      responseType: ResponseType.plain,
    ));
  }

  clearInstance() {
    _instance = null;
  }

  //get请求
  get(String url, Function successCallBack,
      {params, Function errorCallBack}) async {
    _requstHttp(url, successCallBack, GET, params, errorCallBack);
  }

  //post请求
  post(String url, Function successCallBack,
      {params, Function errorCallBack}) async {
    _requstHttp(url, successCallBack, POST, params, errorCallBack);
  }

  _requstHttp(String url, Function successCallBack,
      [String method,
        Map<String, dynamic> params,
        Function errorCallBack]) async {
    String errorMsg = '';
    int code;

    try {
      Response response;
//      _addStartHttpInterceptor(dio); //添加请求之前的拦截器
      if (method == GET) {
        if (params != null && params.isNotEmpty) {
          response = await dio.get(url, queryParameters: params);
        } else {
          response = await dio.get(url);
        }
      } else if (method == POST) {
        if (params != null && params.isNotEmpty) {
          response = await dio.post(url, queryParameters: params);
        } else {
          response = await dio.post(url);
        }
      }

      print('HttpResponse$response');

      code = response.statusCode;
      if (code != 200) {
        errorMsg = '错误码：' + code.toString() + '，' + response.data.toString();
        _error(errorCallBack, errorMsg);
        return;
      }

      Map<String, dynamic> dataMap = json.decode(response.toString());
      if (dataMap != null && !codes.contains(dataMap[CODE])) {
        errorMsg =
            '错误码：' + dataMap[CODE].toString() + '，' + response.data.toString();
        _error(errorCallBack, errorMsg);
        return;
      }

      if (successCallBack != null) {
        successCallBack(dataMap[DATA]);
      }
    } catch (exception) {
      print('error:$exception');
      _error(errorCallBack, exception.toString());
    }
  }

  _error(Function errorCallBack, String error) {
    Fluttertoast.showToast(
        msg: error.toString(),
        toastLength: Toast.LENGTH_SHORT,
        gravity: ToastGravity.CENTER);
    if (errorCallBack != null) {
      errorCallBack(error);
    }
  }

//  _addStartHttpInterceptor(Dio dio) {
//    dio.interceptor.request.onSend = (Options options) {
//      // 在请求被发送之前做一些事情   比如加密的一些操作 或者添加token等参数 对head 或者请求参数进行加工处理
//      Map<String, dynamic> headers = options.headers;
//      Map<String, dynamic> body = options.data;
//      /*request['token'] = '1111111111';
//      headers['addParam'] = 'aaaaaaaaaaaaaaa';*/
//      return options;
//    };
//  }
}
